<template>
  <div class="system-panel-wrapper role-wrapper">
    <search-form
      :search-fields="searchFields"
      :search-form="searchForm"
      :rules="roleRule"
      @handle-search="handleSearch"
    />
    <datagrid
      max-height="calc(100% -50px)"
      :data-list="rolelist"
      :columns="columns"
      :total="roletotal"
      :current-page="currentPage"
      :page-size="pageSize"
      :addable="true"
      :single-page-hide="false"
      @handle-size-change="handleSizeChange"
      @handle-current-change="handleCurrentChange"
      @handle-add="handleAdd"
      @change-switch="changeSwitch"
    >
      <el-table-column align="center" label="操作" width="270">
        <template slot-scope="scope">
          <span
            class="text-btn text-edit"
            @click="handleModify(scope.$index, scope.row)"
          >
            编辑
          </span>
          <span
            class="text-btn text-edit"
            @click="shareRole(scope.$index, scope.row)"
          >
            权限
          </span>
          <span
            v-if="scope.row.groupName !== 'admin'"
            class="text-btn text-delete"
            @click="deleteRow(scope.$index, rolelist)"
          >
            删除
          </span>
        </template>
      </el-table-column>
    </datagrid>
    <!-- 新增/修改弹框 -->
    <dialog-form
      :visible="dialogVisible"
      :empty="empty"
      :form="form"
      :dialog-form="dialogForm"
      :rules="roleRule"
      @handle-cancel="dialogVisible = false"
      @handle-submit="handleSubmit"
    />

    <!-- 树形菜单 -->
    <el-dialog
      class="modify-wrapper"
      title="角色菜单资源树"
      :visible.sync="treeVisible"
      :close-on-click-modal="false"
    >
      <div class="tree_wrapper">
        <el-tree
          ref="treeForm"
          :data="treelist"
          show-checkbox
          node-key="id"
          :default-expanded-keys="['1006']"
          :default-checked-keys="checkedNode"
          :props="defaultProps"
          :check-strictly="false"
        />
      </div>
      <el-footer style="text-align: center">
        <el-button type="info" @click="treeVisible = false">取消</el-button>
        <el-button type="primary" @click="getKeys">提交</el-button>
      </el-footer>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getAction } from '@/api/action';
import SearchForm from '@/components/SearchForm'
import DialogForm from '@/components/DialogForm'
import Datagrid from '@/components/Datagrid'

export default {
  name: 'RoleManage',
  components: { SearchForm, DialogForm, Datagrid },
  data() {
    const validateRoleName = (rule, value, callback) => {
      this.uniqueRoleName(value, callback);
    };
    return {
      urls: { uniqueName: '/api/RoleManagerAction/checkRoleName' },
      currentPage: 1,
      pageSize: 10,
      totalNum: 10,
      checkedNode: [],
      dialogVisible: false,
      empty: '0', // 0 新增，1 修改
      treeVisible: false,
      treeChecked: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      roleRule: {
        groupName: [
          { required: true, message: '此项不能为空', trigger: 'blur' },
          { pattern: /^((?![\u4e00-\u9fa5]).)*$/, message: '角色名称不可为中文！', trigger: 'change' },
          { validator: validateRoleName, trigger: 'change' }
        ],
        groupDescription: [
          { required: true, message: '此项不能为空', trigger: 'blur' }
        ],
        status: [{ required: true, message: '此项不能为空', trigger: 'blur' }]
      },
      searchFields: {
        roleName: '',
        roleStatus: ''
      },
      searchForm: [{
        label: '角色名称',
        field: 'roleName'
      }, {
        label: '状态',
        field: 'roleStatus',
        type: 'select',
        options: [{
          label: '启用',
          value: 0
        }, {
          label: '禁用',
          value: 1
        }]
      }],
      form: {},
      opIndex: 0, // 当前编辑的索引
      dialogForm: [{
        label: '角色名称',
        prop: 'groupName',
      }, {
        label: '角色描述',
        prop: 'groupDescription',
        type: 'textarea',
      }, {
        label: '状态',
        prop: 'status',
        type: 'select',
        options: [{
          label: '启用',
          value: 0
        }, {
          label: '禁用',
          value: 1
        }]
      }],
      columns: [{
        label: '角色名称',
        width: '180',
        prop: 'groupName',
      }, {
        label: '角色描述',
        prop: 'groupDescription',
      }, {
        label: '创建时间',
        prop: 'addDate',
      }, {
        label: '状态',
        prop: 'status',
        type: 'switch'
      }]
    }
  },
  computed: {
    ...mapGetters(['grouparr', 'rolelist', 'treelist', 'checkedlist', 'bnode', 'roletotal', 'pagesize', 'current'])
  },
  created() {
    this.$store.commit('system/SET_ROWS', 10);
    this.$store.commit('system/SET_PAGE', 1);
    this.init();
  },
  methods: {
    init() {
      const obj = {};
      for (const key in this.searchFields) {
        if (Object.hasOwnProperty.call(this.searchFields, key)) {
          const val = this.searchFields[key];
          val.toString() && (obj[key] = val);
        }
      }
      this.$store.dispatch('system/getRoleList', obj);
    },
    handleSearch() {
      this.init();
      // console.log('查询', this.searchFields)
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.$store.commit('system/SET_ROWS', this.pageSize)
      this.init()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.$store.commit('system/SET_PAGE', this.currentPage)
      this.init()
    },
    /* 验证角色名是否重复 */
    async uniqueRoleName(roleName, callback) {
      // 新增 || (编辑 修改了用户名)
      if (this.empty === '0' || (this.empty === '1' && this.rolelist[this.opIndex].groupName !== roleName)) {
        // TODO: 防抖
        const unique = await getAction(this.urls.uniqueName, { roleName }).then(res => {
          return res.data.success;
        })
        if (!unique) {
          callback(new Error('角色名已存在！'));
        } else {
          callback();
        }
        return unique;
      } else {
        callback();
      }
      return true;
    },
    /* 改变开关的值*/
    changeSwitch($event, rows) {
      this.$store.dispatch('system/modifyRoleStatus', { roleId: rows.groupId, status: rows.status })
    },
    /* 删除行*/
    deleteRow(index, rows) {
      this.$confirm('确认删除该行内容？').then((_) => {
        if (this.pageSize < rows.length && this.currentPage > 1) {
          index = (this.currentPage - 1) * this.pageSize + index
        }
        this.$store.commit('system/SET_ROLEID', rows[index].groupId)
        this.$store.dispatch('system/deleteRole').then((res) => {
          if (res.data.success) {
            this.$message({ type: 'success', message: '删除成功！' })
            if (rows.length === 1) {
              this.handleCurrentChange(this.currentPage - 1);
            }
            this.init();
          }
        })
      }).catch((_) => { })
    },
    /* 编辑 */
    handleModify(index, row) {
      this.empty = '1';
      this.dialogVisible = true;
      this.form = { ...row };
      this.opIndex = index;
    },
    /* 新增 */
    handleAdd() {
      this.empty = '0';
      this.dialogVisible = true;
      this.form = {
        addDate: "",
        addUser: "",
        groupDescription: "",
        groupId: "",
        groupName: "",
        status: 0,
        updateDate: null,
        updateUser: null,
      };
    },
    // 树的提交
    getKeys() {
      this.checkedNode = []
      var halfNodes = this.$refs.treeForm.getHalfCheckedKeys()
      var checkKeysArr = this.$refs.treeForm.getCheckedNodes(false, true)
      checkKeysArr.forEach((item) => {
        this.checkedNode.push(item.id)
      })
      this.$store.commit(
        'system/SET_POSTTREELIST',
        this.checkedNode.toString()
      )
      this.$store.commit('system/SET_BNODE', halfNodes.toString())
      this.$store.dispatch('system/postRoleTree').then(res => {
        if (res.data.success) {
          this.$message({ message: '权限修改成功！', type: 'success', })
        }
      })
      this.treeVisible = false
    },
    getCheckedKeys(data, keys, key) {
      var res = []
      recursion(data, false)
      return res

      // arr -> 树形总数据
      // keys -> getCheckedKeys获取到的选中key值
      // isChild -> 用来判断是否是子节点
      function recursion(arr, isChild) {
        var aCheck = []
        for (var i = 0; i < arr.length; i++) {
          var obj = arr[i]
          aCheck[i] = false

          if (obj.children) {
            aCheck[i] = recursion(obj.children, true) ? true : aCheck[i]
            if (aCheck[i]) {
              res.push(obj[key])
            }
          }

          for (var j = 0; j < keys.length; j++) {
            if (obj[key] === keys[j]) {
              aCheck[i] = true
              if (res.indexOf(obj[key]) === -1) {
                res.push(obj[key])
              }
              break
            }
          }
        }
        if (isChild) {
          return aCheck.indexOf(true) !== -1
        }
      }
    },
    shareRole(index, row) {
      this.checkedNode = []
      var newCheckList = []
      this.rowId = row.groupId
      this.$store.commit('system/SET_ROLEID', row.groupId)
      this.$store.dispatch('system/getRoleTree').then(() => {
        this.checkedNode = this.checkedlist
        if (this.bnode.length > 0) {
          this.checkedNode.forEach((item) => {
            if (this.bnode.indexOf(item) === -1) {
              newCheckList.push(item)
            }
          })
          this.checkedNode = newCheckList
        }
        this.treeVisible = true
      })
    },
    /* 提交 */
    handleSubmit(valid) {
      this.dialogVisible = false;
      if (this.empty === '0') {
        this.$store.dispatch('system/addRole', this.form).then(response => {
          if (response.data === 'true') {
            this.$message({ type: 'success', message: '添加成功！' });
            this.init();
          }
        })
      } else {
        this.$store.dispatch('system/modifyRole', this.form).then(response => {
          if (response.data.success) {
            this.$message({ type: 'success', message: '修改成功！' });
            this.init();
          }
        });
      }
      // if (this.activeLabel === 'User') {
      //   this.addUserForm.password = this.$md5(this.addUserForm.password)
      //   this.$store.dispatch('system/addUser', this.addUserForm).then(response => {
      //     this.$store.dispatch('system/getUserList')
      //   })
      // } else if (this.activeLabel === 'Role') {
      //   this.addVisible = false
      //   this.errmsg = false
      //   this.$store.dispatch('system/addRole', this.addRoleForm).then(response => {
      //     this.$store.dispatch('system/getRoleList')
      //   })
      // }
    }
  }
}
</script>

<style lang="scss" scoped>
.tree_wrapper {
  height: 400px;
  margin-bottom: 20px;
  overflow-y: scroll;
}
</style>
